﻿using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Util
{
    public class JwtHelper
    {
        public string BuildToken(IEnumerable<Claim> claims)
        {
            string iss = AppSettingHelper.app(new string[] { "AppSettings", "JwtSetting", "Issuer" });//颁发者
            string aud = AppSettingHelper.app(new string[] { "AppSettings", "JwtSetting", "Audience" });//可以给哪些客户端使用
            string secret = AppSettingHelper.app(new string[] { "AppSettings", "JwtSetting", "SecretKey" });//加密的Key
            int longtime = Convert.ToInt32(AppSettingHelper.app(new string[] { "AppSettings", "JwtSetting", "LongTime" }));//超时时长
            //需要加密：需要加密key:
            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            JwtSecurityToken token = new JwtSecurityToken(
            issuer: iss,
             audience: aud,
             claims: claims,
            notBefore: DateTime.UtcNow,
             expires: DateTime.Now.AddSeconds(longtime),
             signingCredentials: creds);
            string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
            return returnToken;
        }
        /// <summary>
        /// 颁发JWT字符串
        /// </summary>
        /// <param name="tokenModel"></param>
        /// <returns></returns>
        public static string IssueJwt(TokenModel tokenModel)
        {
            //获取Appsetting配置
            string iss = AppSettingHelper.app(new string[] { "AppSettings", "JwtSetting", "Issuer" });//颁发者
            string aud = AppSettingHelper.app(new string[] { "AppSettings", "JwtSetting", "Audience" });//可以给哪些客户端使用
            string secret = AppSettingHelper.app(new string[] { "AppSettings", "JwtSetting", "SecretKey" });//加密的Key
            int longtime = Convert.ToInt32(AppSettingHelper.app(new string[] { "AppSettings", "JwtSetting", "LongTime" }));//超时时长

            //定义需要使用的Claim
            var claims = new List<Claim>
            {
                new Claim(JwtRegisteredClaimNames.Jti, $"{iss}"),
                new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                //这个就是过期时间，目前是过期180秒，可自定义，注意JWT有自己的缓冲过期时间
                new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddSeconds(longtime)).ToUnixTimeSeconds()}"),
                new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(longtime).ToString()),
                new Claim(JwtRegisteredClaimNames.Iss,iss),
                new Claim(JwtRegisteredClaimNames.Aud,aud),
            };
            //秘钥 (SymmetricSecurityKey 对安全性的要求，密钥的长度太短会报出异常)
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var jwt = new JwtSecurityToken(
                issuer: iss,
                claims: claims,
                signingCredentials: creds);

            var jwtHandler = new JwtSecurityTokenHandler();
            var encodedJwt = jwtHandler.WriteToken(jwt);

            return encodedJwt;
        }

        /// <summary>
        /// 解析
        /// </summary>
        /// <param name="jwtStr"></param>
        /// <returns></returns>
        public static TokenModel SerializeJwt(string jwtStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
            object role;
            object time;
            object businessId;
            try
            {
                jwtToken.Payload.TryGetValue(ClaimTypes.Expiration, out time);
                jwtToken.Payload.TryGetValue(ClaimTypes.Role, out role);
                jwtToken.Payload.TryGetValue(ClaimTypes.Sid, out businessId);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            // 获取特定声明的值
            string UidClaimValue = jwtToken.Claims.FirstOrDefault(c => c.Type == "Uid")?.Value;
            string RoleClaimValue = jwtToken.Claims.FirstOrDefault(c => c.Type == "Role")?.Value;
            var tm = new TokenModel
            {
                Uid = UidClaimValue.ToString(),
                Role = RoleClaimValue.ToString()
            };
            return tm;
        }

        ///
        public static string GetNewToken(string jwtStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
            object time;
            jwtToken.Payload.TryGetValue(ClaimTypes.Expiration, out time);
            var getSeconds = (DateTime.Parse(time.ToString()) - DateTime.Now).TotalMinutes;
            if (getSeconds < 30 && getSeconds > 0)
            {
                string t = IssueJwt(SerializeJwt(jwtStr));
                return t;
            }
            return "";
        }
    }
}
